import Vue from 'vue'
import Vuex from 'vuex'
import { delCookie } from '../utils/fetch'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    userInfo: null,
    courses: [],
    lesson: [],
    tasks: [],
    tasking: []
  },
  getters: {
    isTeacher: state => {
      return state.userInfo && state.userInfo.role === '2'
    },
    getCourseById: (state) => (id) => {
      return state.courses.find(item => item.id === id)
    }
  },
  mutations: {
    setUserInfo (state, userInfo) {
      state.userInfo = userInfo
      sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
      sessionStorage.setItem('token', userInfo.token)
    },
    logout (state, userInfo) {
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('userInfo')
      delCookie('csrftoken')
      state.userInfo = null
      state.courses = []
      state.lesson = []
      state.tasks = []
    },
    setCourses (state, courses) {
      state.courses = courses
    },
    setLesson (state, courses) {
      state.lesson = courses
    },
    setTasks (state, tasks) {
      state.tasks = tasks
    },
    setTasking (state, tasking) {
      state.tasking = tasking
    },
    setQuestions (state, items) {
      // console.log(items)
      state.tasks.map((item) => { if (item.assignment_id === items.task.assignment_id) { item.questions = items.questions } })
      state.tasking.map((item) => { if (item.assignment_id === items.task.assignment_id) { item.questions = items.questions } })
    }
  }
})

export default store
